package com.java.huxb.day04;

import com.java.huxb.day04.entity.Student;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author huxb
 * @date 2020/3/7 0007 上午 8:25
 * 通过反射api获取类的属性，方法，名字
 */
public class Test {

    public static void main(String[] args) throws Exception {
        List<Student> studentList = new ArrayList<>(10);
        studentList.add(new Student("学生一", 12, (byte)0));
        Class<? extends Student> aClass = studentList.get(0).getClass();
        Student student = aClass.newInstance(); //调用无参构造方法
        System.out.println(student);
        Method setName = aClass.getMethod("setName", String.class);
        setName.invoke(studentList.get(0), "hello");
        System.out.println(studentList.get(0));

        //访问私有属性
        Student stu = aClass.newInstance();
        Field name = aClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(stu, "学生名字");
        System.out.println(stu);

    }
}
